import java.util.Scanner;

public class Sum2DArrays {
    
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        System.out.printf("Enter number of rows: ");
        int numRows = scanner.nextInt();
        System.out.printf("Enter number of columns: ");
        int numCols = scanner.nextInt();
        
        if(numRows <= 0 || numCols <= 0){
        	System.out.printf("Error: Invalid number of rows or columns");
        	System.exit(1);
        }
        
        int[][] matrix1 = new int[numRows][numCols], matrix2 = new int[numRows][numCols],
           matrix3 = new int[numRows][numCols];
        
        // Read matrix1 row-wise
        System.out.printf("Enter %d * %d elements of matrix1 row-wise:%n", numRows, numCols);
        for(int r = 0; r < matrix1.length; r++){
        	for(int c = 0; c < matrix1[r].length; c++){
        		matrix1[r][c] = scanner.nextInt();
        	}	
        }
        
        // Read matrix2 row-wise
        System.out.printf("Enter %d * %d elements of matrix2 row-wise:%n", numRows, numCols);
        for(int r = 0; r < matrix2.length; r++){
        	for(int c = 0; c < matrix2[r].length; c++){
        		matrix2[r][c] = scanner.nextInt();
        	}	
        }
        
        // Add matrix1 and matrix2 row-wise
        for(int r = 0; r < matrix3.length; r++){
        	for(int c = 0; c < matrix3[r].length; c++){
        		matrix3[r][c] = matrix1[r][c] + matrix2[r][c];
        	}	
        }
        
        
        System.out.printf("%nThe sum of matrix1 and matrix2 is:%n");
        
        // Display matrix3 row-wise
        for(int r = 0; r < matrix3.length; r++){
        	for(int c = 0; c < matrix3[r].length; c++){
        		System.out.printf("%3d  ", matrix3[r][c]);
        	}
        	
        	System.out.printf("%n");	
        }
    }
}
